﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMCSerialTransfer.Packets
{
    class SndDataPacket: APacket
    {
        public override bool Packet(byte[] Data)
        {
            return Process(Data);
        }

        public override bool EndProcess(bool Ok)
        {
            int len;
            byte[] Data;
            if (Ok)
            {
                Globals.Message = ".";
                if (Globals.FileLen - Globals.FilePtr > 128)
                    len = 129;
                else
                    len = Globals.FileLen - Globals.FilePtr + 1;
                Data = new byte[len];
                Globals.FileStream.Read(Data, 1, Data.Length-1);
                Data[0] = (byte)Globals.ACKType.E_ACK;
                Globals.Create((byte)CommFactory.Command.SndACK, Globals.DataPacket);
                Globals.PacketSize = Globals.DataPacket.Length;
                Globals.FileStream.Read(Globals.DataPacket, 0, Globals.DataPacket.Length);
                Globals.FilePtr += len;
                Globals.ProgressEvent = Globals.ProgressType.Add;
                Globals.Message = ".";
                if (Globals.FilePtr >= Globals.FileLen)
                {
                    Globals.FileStream.Close();
                    Globals.Message += "\nFile Sent\n";
                    Globals.ProgressEvent = Globals.ProgressType.Clear;
                }
            }
            else
            {
                Globals.Message="\nCRC Error. Retrying\n";
                ACKPacket(Globals.ACKType.E_ERR);
            }
            return Ok;
        }
    }
}
